package cn.iwit;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.iwit.model.Constant;
import cn.iwit.model.SysFunc;
import cn.iwit.model.UserInfo;
import cn.iwit.util.BusiException;
import cn.iwit.util.HttpUtil;

@Configuration
public class LoginInterceptorConfig extends WebMvcConfigurerAdapter {

	
	public void addInterceptors(InterceptorRegistry registry) {
		
		 registry.addInterceptor(new HandlerInterceptorAdapter() {

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BusiException, IOException {
				String url = request.getRequestURI();
				boolean isajaxreq = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
				//boolean isajaxreq = "x-requested-with".equals(request.getHeader("Access-Control-Request-Headers"));
				
				try {
					UserInfo userInfo=null;
					try {
						  userInfo = (UserInfo) HttpUtil.getAttribute(Constant.USERINFO);
					} catch (Exception e) {
						throw new BusiException("ZG0001", "登录超时或会话失效");
					}
					
					//是否超时
					
					if (userInfo==null) {
						//判断请求的类型，如果是ajax，则返回标准的错误ajax异常，否则重定向到登录页面
						throw new BusiException("ZG0001", "登录超时或会话失效");
					}
					
					String access_token = (String) HttpUtil.getAttribute(Constant.ACCESS_TOKEN);
					if (StringUtils.isEmpty(access_token)){
						throw new BusiException("ZG0001", "登录超时或会话失效");
					}
						
					
					//检查用户是否可以访问此菜单
					boolean bln = accessMenu(userInfo,url);
					if (!bln) {
						throw new BusiException("ZG0002", "无权限访问此菜单");
					}
				} catch (BusiException e) {
						/*if(isajaxreq){
							throw e;
						}else{
							response.sendRedirect(request.getContextPath() + "/");
						}*/
				}
				
				return true;
			}
		}).addPathPatterns("/sys/**","/admin/**");///sys/**","/admin/**
	}
	
	
	/**
	 * 检查用户是否可以访问此菜单
	 * @param request
	 * @param userid
	 * @param url
	 * @return
	 * @throws BaseException
	 */
	private boolean accessMenu(UserInfo userInfo,String url) throws BusiException {
		List<SysFunc> resultList = userInfo.getSysFuncs();
		if(resultList==null || resultList.size()==0){
			return false;
		}
		for(SysFunc sysFunc:resultList){
			if(url.equals(sysFunc.getUrl())){
				return true;
			}
		}
	    return false;
	}
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

}
